<!--
 * @Author: weisheng
 * @Date: 2021-12-22 15:19:08
 * @LastEditTime: 2023-05-10 10:04:19
 * @LastEditors: weisheng
 * @Description: 
 * @FilePath: \uniapp-vue3-fant-ts\src\pages\cart\Cart.vue
 * 记得注释
-->
<template>
	<view class="list-container">
		<NavBar ref="navRef" @itemTap="itemTapHandler" :select-index="state.selectIndex"
			:category-list="state.categoryList"></NavBar>
		<SubBar @itemTap="subItemTapHandler" :select-index="state.subIndex" :category-list="state.subCategoryList">
		</SubBar>
		<swiper circular class="swiper-box" :duration="300" :current="state.subIndex" @change="swiperChange">
			<swiper-item @touchstart="fingerStart" @touchend="fingerEnd" class="swiper-item" :key="swiper.id"
				v-for="(swiper, indexPath) in state.subCategoryList">
				<scroll-view @scrolltoupper="refreshAction" @scrolltolower="moreAction" scroll-y="true"
					class="list-scroll">
					<!-- #ifdef MP-WEIXIN-->
					<block v-if="state.subIndex == indexPath">
						<wContainer :columnNumber="2">
							<wItem v-for="(item, index) in state.productList" :key="index">
								<view class="box">
									<ProductItem :product-obj="item" :index="index"></ProductItem>
								</view>
							</wItem>
						</wContainer>
					</block>
					<!-- #endif -->
					<!-- #ifdef APP -->
					<view class="scroll-item" v-for="(item, index) in state.productList">
						<ProductItem :product-obj="item" :index="index"></ProductItem>
					</view>
					<!-- #endif -->
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script lang="ts" setup>
	import { getCategoryList, loginAPI, getProductListWithCategory } from '@/api/DemoApi'
	import { onMounted, reactive, ref } from 'vue'
	import { nextTick } from 'vue'
	// import {} from 'loadsh'
	import NavBar from '@/components/NavBar/NavBar.vue'
	import SubBar from '@/components/SubBar/SubBar.vue'
	import ProductItem from '@/components/ProductItem/ProductItem.vue'
	import wContainer from '@/components/simple-waterfall/components/simple-waterfall/w-container.vue'
	import wItem from '@/components/simple-waterfall/components/simple-waterfall/w-item.vue'
	import { cloneDeep } from 'lodash-es'
	import { onPullDownRefresh } from '@dcloudio/uni-app'

	const navRef = ref()
	const state = reactive({
		categoryList: [],
		subCategoryList: [],
		productList: [],
		selectIndex: 0,
		subIndex: 0,
		heightList: [],
		page: 1,
		currentCategoryId: '',
		lastSubIndex: 0,
		clientX: 0,
		switchStop: false
	})

	const refreshAction = () => {
		state.page = 1
		getProductList(false)
		// uni.startPullDownRefresh();
	}

	onPullDownRefresh(() => {
		state.page = 1
		getProductList(false)
		setTimeout(function () {
			uni.stopPullDownRefresh()
		}, 1000)
	})

	const moreAction = () => {
		state.page += 1
		getProductList(true)
	}

	//一开始手指活动的方向
	const fingerStart = (e : any) => {
		state.clientX = e.changedTouches[0].clientX
	}
	// 判断页面是上滑还是下滑
	const fingerEnd = (e : any) => {
		const clientX = e.changedTouches[0].clientX - state.clientX
		// 这里处理sub 分类小于等于2的情况
		if (state.subCategoryList.length <= 2) {
			if (state.subCategoryList.length == 1) {
				if (clientX < -150) {
					//切换下一个分类
					if (state.selectIndex !== state.categoryList.length - 1) {
						state.switchStop = true;
						switchNextCategory()
					}
				}
				if (clientX > 150) {
					//切换上一个分类
					if (state.selectIndex !== 0) {
						state.switchStop = true;
						switchPreCategory()
					}
				}
			} else {
				if (state.subIndex == 1) {
					if (clientX < -150) {
						//切换下一个分类
						if (state.selectIndex !== state.categoryList.length - 1) {
							state.switchStop = true;
							switchNextCategory()
						}
					}
				}
				if (state.subIndex == 0) {
					if (clientX > 150) {
						//切换上一个分类
						if (state.selectIndex !== 0) {
							state.switchStop = true;
							switchPreCategory()
						}
					}
				}
			}
		}
	}

	const switchNextCategory = () => {
		state.selectIndex += 1
		state.subCategoryList = state.categoryList[state.selectIndex]['children']
		state.subIndex = 0
		state.currentCategoryId = state.subCategoryList[state.subIndex]['id']
		state.page = 1
		state.productList = []
		getProductList(false)
		navRef.value.scrollToView()
		setTimeout(function () {
			state.switchStop = false;
		}, 500);
	}

	const switchPreCategory = () => {
		state.selectIndex -= 1
		state.subCategoryList = state.categoryList[state.selectIndex]['children']
		state.subIndex = state.subCategoryList.length - 1
		state.currentCategoryId = state.subCategoryList[state.subIndex]['id']
		state.page = 1
		state.productList = []
		getProductList(false)
		navRef.value.scrollToView()
		setTimeout(function () {
			state.switchStop = false;
		}, 500);
	}

	const loginAction = () => {
		let params = {
			tel: '18171171929',
			smsCode: '999999'
		}
		loginAPI(params)
			.then((resp : any) => {
				uni.setStorageSync('lx-ticket', resp.data)
				getCategoryListAction()
			})
			.catch((error) => {
			})
	}

	const getCategoryListAction = () => {
		getCategoryList()
			.then((res : any) => {
				if (res.status === 0) {
					let list = cloneDeep(res.data[0]['children'])
					list.unshift({
						name: '全部',
						id: res.data[0]['id'],
						children: [
							{
								name: '全部',
								id: res.data[0]['id']
							}
						]
					})
					state.categoryList = list
					list.forEach((item1 : any, index1 : number) => {
						if (index1 > 0) {
							item1.children.unshift({
								id: item1.id,
								name: '不限',
								children: []
							})
						}
					})
					state.subCategoryList = [
						{
							name: '全部',
							id: res.data[0]['id'],
							children: []
						}
					]
					state.currentCategoryId = state.subCategoryList[0]['id']
					getProductList(false)
				}
			})
			.catch((error) => {
			})
	}

	const itemTapHandler = (index : number) => {
		state.selectIndex = index
		state.subCategoryList = state.categoryList[state.selectIndex]['children']
		state.subIndex = 0
		state.currentCategoryId = state.subCategoryList[state.subIndex]['id']
		state.page = 1
		state.productList = []
		getProductList(false)
		navRef.value.scrollToView()
	}

	const subItemTapHandler = (index : number) => {
		state.subIndex = index
		state.currentCategoryId = state.subCategoryList[state.subIndex]['id']
		state.page = 1
		// state.productList = [];
		nextTick(() => {
			getProductList(false)
		})
	}

	const swiperChange = (e : any) => {
		if (state.switchStop) return;
		state.subIndex = e.detail.current
		if (state.subCategoryList.length == 2) {
			state.currentCategoryId = state.subCategoryList[state.subIndex]['id']
			state.page = 1
			state.productList = []
			getProductList(false)
		} else {
			if (
				(state.lastSubIndex == state.subCategoryList.length - 1 && state.subIndex == 0) ||
				(state.lastSubIndex == 0 && state.subIndex == state.subCategoryList.length - 1)
			) {
				if (state.subIndex == 0) {
					// 这里要切换一级菜单 往后切换
					if (state.selectIndex !== state.categoryList.length - 1) {
						switchNextCategory()
					}
				} else {
					// 这里要切换一级菜单 往回切回
					if (state.selectIndex !== 0) {
						switchPreCategory()
					}
				}
			} else {
				state.currentCategoryId = state.subCategoryList[state.subIndex]['id']
				state.page = 1
				state.productList = []
				getProductList(false)
			}
		}
		state.lastSubIndex = e.detail.current
	}

	const getProductList = (bool : boolean) => {
		let params = {
			pageSize: 10,
			pageNum: state.page,
			categoryId: state.currentCategoryId
		}
		getProductListWithCategory(params).then((res : any) => {
			if (res.status == 0) {
				let list = res.data.items
				list.forEach((item : any) => {
					item.remainTime = diffRemainTime(item.discountStartTime, item.discountEndTime)
				})
				if (bool) {
					state.productList = state.productList.concat(list)
				} else {
					state.productList = list
				}
			} else {
			}
		})
	}

	const diffRemainTime = (start : string, end : string) => {
		let start_date = new Date(start).getTime() //新建一个日期对象，默认现在的时间
		let end_date = new Date(end).getTime() //设置过去的一个时间点，"yyyy-MM-dd HH:mm:ss"格式化日期
		let difftime : number = (end_date - start_date) / 1000 //计算时间差,并把毫秒转换成秒
		let days = parseInt(String(difftime / 86400)) // 天  24*60*60*1000
		let hours = parseInt(String(difftime / 3600)) - 24 * days // 小时 60*60 总小时数-过去的小时数=现在的小时数
		let minutes = parseInt(String((difftime % 3600) / 60)) // 分钟 -(day*24) 以60秒为一整份 取余 剩下秒数 秒数/60 就是分钟数
		return days + '天' + hours + '小时' + minutes + '分钟'
	}

	onMounted(() => {
		loginAction()
	})
</script>

<style lang="scss" scoped>
	.list-container {
		height: 100%;
		background-color: #ededed;

		.swiper-box {
			height: calc(100% - 80px);

			.swiper-item {
				height: 100%;
				// background-color: red;

				.list-scroll {
					height: 100%;
					/* #ifdef APP */
					padding-left: -20upx;
					// background-color: yellow;
					/* #endif */

					/* #ifdef APP */
					.scroll-item {
						float: left;
						width: calc((100% - 60upx) / 2);
						margin-left: 20upx;
					}

					/* #endif */
				}
			}
		}
	}
</style>